//
//  GZ_PlayerPageVC.m
//  B段项目
//
//  Created by 高哲 on 15/11/5.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "GZ_PlayerPageVC.h"
#import "GZplayArrayTVcell.h"
#import "UIImage+Blur.h"
#import "GZ_Music.h"
#import <AVFoundation/AVFoundation.h>
@interface GZ_PlayerPageVC ()<UITableViewDataSource, UITableViewDelegate>
@property(nonatomic, strong)UIImageView *bgImageView;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, strong)UIButton *button1;
@property(nonatomic, strong)UIButton *button2;
@property(nonatomic, strong)UIButton *button3;

@property(nonatomic, strong)UIScrollView *scrollView;
@property(nonatomic, strong)UIWebView *webView;

@property(nonatomic, strong)NSString *mp3String;
@property(nonatomic, strong)XMN_ProgressHUD *progressView;

@property(nonatomic, strong)NSString *urlString;
@property(nonatomic, strong)NSString *bodyString;

@property(nonatomic ,strong)UITableView *tableView;

@property(nonatomic, strong)GZ_Music *playMusic;
@property(nonatomic, strong)UIProgressView *progressView2;//播放进度条

@property(nonatomic, strong)UIImageView *photoImageView;
@property(nonatomic, strong)UIImageView *blueImageView;
@property(nonatomic, strong)UIImageView *wyImageView;

@property(nonatomic, strong)UILabel *totleTimeLabel;
@property(nonatomic, strong)UILabel *currentTimeLabel;

@property(nonatomic, strong)CABasicAnimation *basicAnimation2;
@end

@implementation GZ_PlayerPageVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = _radioModel.title;
   
    //音乐播放,上下一首模块
    _bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, ScreenHeight - 64 - 70 * FitHeight, ScreenWidth, 70 * FitHeight)];
    _bgImageView.image = [UIImage imageNamed:@"GZbg.png"];
    _bgImageView.userInteractionEnabled = YES;
    [self.view addSubview:_bgImageView];
    
    _button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    _button1.frame = CGRectMake(60 * FitWidth, 20 * FitHeight, 30 * FitWidth, 30 * FitHeight);
    [_button1 setImage:[UIImage imageNamed:@"GZzuo.png"] forState:UIControlStateNormal];
    _button1.tintColor = [UIColor darkGrayColor];
    [_button1 addTarget:self action:@selector(upSongAction) forControlEvents:UIControlEventTouchUpInside];
    [_bgImageView addSubview:_button1];
    
    _button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    _button2.frame = CGRectMake(_button1.frame.size.width + _button1.frame.origin.x + 82.5 * FitWidth, _button1.frame.origin.y - 3 * FitHeight, 35 * FitWidth, 35 * FitHeight);
    _button2.tintColor = [UIColor darkGrayColor];
    [_button2 setImage:[UIImage imageNamed:@"GZzanting.png"] forState:UIControlStateNormal];
    [_button2 addTarget:self action:@selector(playSongAction) forControlEvents:UIControlEventTouchUpInside];
    [_bgImageView addSubview:_button2];
    
    _button3 = [UIButton buttonWithType:UIButtonTypeSystem];
    _button3.frame = CGRectMake(_button2.frame.size.width + _button2.frame.origin.x + 82.5 * FitWidth, _button1.frame.origin.y, 30 * FitWidth, 30 * FitHeight);
    _button3.tintColor = [UIColor darkGrayColor];
    [_button3 setImage:[UIImage imageNamed:@"GZyou.png"] forState:UIControlStateNormal];
    [_button3 addTarget:self action:@selector(downSongAction) forControlEvents:UIControlEventTouchUpInside];
    [_bgImageView addSubview:_button3];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, _scrollView.frame.size.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc] init];
    [_tableView NightWithType:UIViewColorType2];
    [_scrollView addSubview:_tableView];

    
}

- (void)loadView
{
    [super loadView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationCenterAction:) name:@"sendFlag" object:nil];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Music"];
    
    
  //播放功能页面 添加在view上
    _flag = 0;
  
    //滚动图
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64 - 70 * FitHeight)];
    _scrollView.contentSize = CGSizeMake(ScreenWidth * 3, ScreenHeight - 64 - 70 * FitHeight);
    _scrollView.contentOffset = CGPointMake(ScreenWidth, 0);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = YES;
    _scrollView.bounces = NO;
    [self.view addSubview:_scrollView];
    
    _progressView = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _progressView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _progressView.XMN_label.text = @"Waiting...";
    [self.view addSubview:_progressView];
    
    
    //web页的设置
    //滚动视图第二页
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(ScreenWidth * 2, 0, ScreenWidth, _scrollView.frame.size.height)];
     [_scrollView addSubview:_webView];
    
    //播放页面背景图
    _blueImageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth, 0, ScreenWidth, _scrollView.frame.size.height)];
    _blueImageView.userInteractionEnabled = YES;
    UIImage *treeImage = [UIImage imageNamed:@"GZblue.png"];
    _blueImageView.image = [treeImage boxblurImageWithBlur:0.6];
    [_scrollView addSubview:_blueImageView];
    
    //播放器背景图
    _wyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(45 * FitWidth, 95 * FitHeight, 295 * FitWidth, 308 * FitHeight)];
    _wyImageView.image = [UIImage imageNamed:@"GZwy"];
    [_blueImageView addSubview: _wyImageView];

    //音乐转圈图
    _photoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(58 * FitWidth, 80 * FitHeight, 178 * FitWidth, 178 * FitHeight)];
    _photoImageView.backgroundColor = [UIColor colorWithRed:0.06 green:0.06 blue:0.06 alpha:1];
    _photoImageView.layer.cornerRadius =89 * FitHeight;
    _photoImageView.layer.masksToBounds = YES;
    [_wyImageView addSubview:_photoImageView];
    
    _basicAnimation2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    _basicAnimation2.fromValue = [NSNumber numberWithInteger:0];
    _basicAnimation2.toValue = [NSNumber numberWithInteger:M_PI * 100];
    [_basicAnimation2 setDuration:900];
    [_basicAnimation2 setRepeatCount:NSIntegerMax];
    ;
    
    _progressView2 = [[UIProgressView alloc] initWithFrame:CGRectMake(80 * FitWidth, _wyImageView.frame.size.height + _wyImageView.frame.origin.y + 50 * FitHeight, ScreenWidth - 160 * FitWidth, 30)];
    [_blueImageView addSubview:_progressView2];

    UIButton *tableButton = [UIButton buttonWithType:UIButtonTypeSystem];
    tableButton.frame = CGRectMake(_progressView2.frame.origin.x + _progressView2.frame.size.width - 25 * FitWidth, _progressView2.frame.origin.y - 50, 25 * FitWidth, 25 * FitHeight);
    [tableButton setImage:[UIImage imageNamed:@"GZliebiao.png"] forState:UIControlStateNormal];
    [tableButton addTarget:self action:@selector(tableAction) forControlEvents:UIControlEventTouchUpInside];
    tableButton.tintColor = [UIColor lightGrayColor];
    [_blueImageView addSubview:tableButton];
    
    
    _totleTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_progressView2.frame.size.width + _progressView2.frame.origin.x + 5 * FitWidth, _progressView2.frame.origin.y - 15 * FitHeight, 60 * FitWidth, 30 * FitHeight)];
    _totleTimeLabel.textAlignment = NSTextAlignmentLeft;
    _totleTimeLabel.font = [UIFont systemFontOfSize:13];
    _totleTimeLabel.textColor = [UIColor lightGrayColor];
    [_blueImageView addSubview:_totleTimeLabel];
    
    _currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_progressView2.frame.origin.x - 65 * FitWidth, _totleTimeLabel.frame.origin.y, _totleTimeLabel.frame.size.width, _totleTimeLabel.frame.size.height)];
    _currentTimeLabel.textAlignment = NSTextAlignmentRight;
    _currentTimeLabel.textColor = [UIColor lightGrayColor];
    _currentTimeLabel.font = [UIFont systemFontOfSize:13];
    [_blueImageView addSubview:_currentTimeLabel];
    
    _urlString = @"http://api2.pianke.me/ting/info";
    _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=5AA12B08-7AD2-4ED0-B4EB-571025443952&tingid=%@&version=3.0.6", _tingString];
          [self getData];
}


- (void)getData
{
    if (_dataSourceArray.count == 0) {
        [HTTPMethod getDataByString:_urlString BODYDic:[ChangeString changeStringToDictionary:_bodyString] WithDataBlock:^(id data) {
           _dataSourceArray = [NSMutableArray array];
            NSDictionary *dataDic = [data valueForKey:@"data"];
            NSArray *moretingArray = [dataDic valueForKey:@"moreting"];
            for (NSDictionary *modelDic in moretingArray) {
                GZ_RadioModel *model = [[GZ_RadioModel alloc] init];
                [model setValuesForKeysWithDictionary:modelDic];
                [_dataSourceArray addObject:model];
            }
           
            [_tableView reloadData];
            
        }];

    }
    
    [HTTPMethod getDataByString:_urlString BODYDic:[ChangeString changeStringToDictionary:_bodyString] WithDataBlock:^(id data) {
        
        NSDictionary *dataDic = [data valueForKey:@"data"];
        NSDictionary *playInfoDic = [dataDic valueForKey:@"playInfo"];
        self.title = [playInfoDic valueForKey:@"title"];
        
        NSURL *url = [NSURL URLWithString:[playInfoDic valueForKey:@"webview_url"]];
        NSURLRequest *requeset = [NSURLRequest requestWithURL:url];
        [_webView loadRequest:requeset];
    
        [_photoImageView sd_setImageWithURL:[NSURL URLWithString:[playInfoDic valueForKey:@"imgUrl"]] placeholderImage:[UIImage imageNamed:@"zhanwei.png"]];
        
        //消息中心
        [[NSNotificationCenter defaultCenter] postNotificationName:@"songBGimageView" object:[playInfoDic valueForKey:@"imgUrl"]];
         [[NSNotificationCenter defaultCenter] postNotificationName:@"songName" object:[playInfoDic valueForKey:@"title"]];
        
        
        
        [_photoImageView.layer addAnimation:_basicAnimation2 forKey:@"rotation"];
        
        
        [[GZ_Music shareInstance] playMusicWith:[playInfoDic valueForKey:@"musicUrl"]];
        [GZ_Music shareInstance].block = ^(CGFloat progress, CGFloat totleTime, CGFloat current){
            [_progressView2 setProgress:progress animated:YES];
            _totleTimeLabel.text = [NSString stringWithFormat:@"%.2f", totleTime];
            _currentTimeLabel.text = [NSString stringWithFormat:@"%.2f", current];
        };
        
        
        [_progressView removeFromSuperview];
    }];
}



//播放按钮设置
- (void)upSongAction
{
    _currentIndexpathRow --;
    if (_currentIndexpathRow < 0) {
        _currentIndexpathRow = _dataSourceArray.count - 1;
    }
    if (_currentIndexpathRow >= 0) {
        _urlString = @"http://api2.pianke.me/ting/info";
        _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=5AA12B08-7AD2-4ED0-B4EB-571025443952&tingid=%@&version=3.0.6",[_dataSourceArray[_currentIndexpathRow] tingid]];
        _progressView = [[XMN_ProgressHUD alloc]initWithFrame:self.view.frame];
        _progressView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
        _progressView.XMN_label.text = @"Waiting...";
        [self.view addSubview:_progressView];
        [self getData];
    }
}

- (void)playSongAction
{
    if (_flag == 0) {
        [_button2 setImage:[UIImage imageNamed:@"GZplay.png"] forState:UIControlStateNormal];
        [[GZ_Music shareInstance].player pause];
        _flag = 1;
        [_photoImageView.layer removeAnimationForKey:@"rotation"];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"Music"];
    }else{
        [_button2 setImage:[UIImage imageNamed:@"GZzanting.png"] forState:UIControlStateNormal];
[[GZ_Music shareInstance].player play];
        _flag = 0;
        [_photoImageView.layer addAnimation:_basicAnimation2 forKey:@"rotation"];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"Music"];
    }
    
    
}
-(void)downSongAction
{
    _currentIndexpathRow ++;
    if (_currentIndexpathRow >= _dataSourceArray.count) {
        _currentIndexpathRow = 0;
    }
    if (_currentIndexpathRow < _dataSourceArray.count) {
        _urlString = @"http://api2.pianke.me/ting/info";
        _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=5AA12B08-7AD2-4ED0-B4EB-571025443952&tingid=%@&version=3.0.6",[_dataSourceArray[_currentIndexpathRow] tingid]];
        _progressView = [[XMN_ProgressHUD alloc]initWithFrame:self.view.frame];
        _progressView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
        _progressView.XMN_label.text = @"Waiting...";
        [self.view addSubview:_progressView];
        [self getData];
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
      _currentIndexpathRow = indexPath.row;
    _urlString = @"http://api2.pianke.me/ting/info";
    _bodyString = [NSString stringWithFormat:@"auth=&client=1&deviceid=5AA12B08-7AD2-4ED0-B4EB-571025443952&tingid=%@&version=3.0.6",[_dataSourceArray[_currentIndexpathRow] tingid]];
    _progressView = [[XMN_ProgressHUD alloc]initWithFrame:self.view.frame];
    _progressView.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _progressView.XMN_label.text = @"Waiting...";
    [self.view addSubview:_progressView];

    
    [self getData];
  
    [_scrollView setContentOffset:CGPointMake(ScreenWidth, 0) animated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 55;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    GZplayArrayTVcell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[GZplayArrayTVcell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    if (_dataSourceArray.count != 0) {
        cell.radioModel = [_dataSourceArray objectAtIndex:indexPath.row];
    }
    [cell NightWithType:UIViewColorTypeNormal];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.2);
//        [UIView animateWithDuration:0.5 animations:^{
//            cell.layer.transform = CATransform3DMakeScale(1, 1, 0.2);
//        }];
    return cell;
   }

- (void)tableAction
{
    [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

- (void)notificationCenterAction:(NSNotification *)notification
{
    if ([[notification object] integerValue] == 0) {
        [_button2 setImage:[UIImage imageNamed:@"GZplay.png"] forState:UIControlStateNormal];
        [[GZ_Music shareInstance].player pause];
        _flag = 1;
        [_photoImageView.layer removeAnimationForKey:@"rotation"];
    }else{
        [_button2 setImage:[UIImage imageNamed:@"GZzanting.png"] forState:UIControlStateNormal];
        [[GZ_Music shareInstance].player play];
        _flag = 0;
        [_photoImageView.layer addAnimation:_basicAnimation2 forKey:@"rotation"];

    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
